package com.pdstudio.carrecom.ui.activity.owner;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;
import com.pdstudio.carrecom.R;
import com.pdstudio.carrecom.api.HttpExecuteJson;
import com.pdstudio.carrecom.api.HttpExecuteJson.httpReturnJson;
import com.pdstudio.carrecom.api.ServiceHelper;
import com.pdstudio.carrecom.app.AppContext;
import com.pdstudio.carrecom.app.UIHelper;
import com.pdstudio.carrecom.bean.CarSelectInfo;
import com.pdstudio.carrecom.bean.ResultInfo;
import com.pdstudio.carrecom.logger.Logger;
import com.pdstudio.carrecom.tools.JsonUtil;
import com.pdstudio.carrecom.tools.StringUtils;
import com.pdstudio.carrecom.ui.activity.ActivitySelectCommon;

/**
 * 
 * 类: ActivityBxxb <br>
 * 描述: 我是车主——保险续保 <br>
 * 作者: ws <br>
 * 时间: 2015-6-15 下午11:32:03
 */
public class ActivityBxxb extends Activity implements OnClickListener {

	private static final String TAG = "ActivityMessage";

	private static final int MSG_WHAT_ABOUT = 1;
	private List<CarSelectInfo> mDatas = new ArrayList<>();

	private TextView txtTitle;
	private ImageView ivBack;
	private int type = 111111;

	private AppContext mAppContext = AppContext.getInstance();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_owner_bxxb);
		initTitle();
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			Logger.i(TAG, msg);
			switch (msg.what) {
			case MSG_WHAT_ABOUT:// 关于

				break;

			case 4: {// 选择类型
				// UIHelper.showSelectBrandActivity(ActivityNewCar.this,
				// mDatas);
				type = 111111;
				Intent intent = new Intent(ActivityBxxb.this,
						ActivitySelectCommon.class);
				intent.putExtra("title", "选择类型");
				intent.putExtra("datas", (Serializable) mDatas);
				startActivityForResult(intent, type);
			}
				break;

			default:
				break;
			}
		}
	};

	private LinearLayout mLinearLayoutSelectType;

	private EditText mSelectDate;

	private EditText mUserName;

	private EditText mPhone;

	private Button mNextStep;

	private TextView msSerial;

	private TextView msType;

	private TextView msBrand1;

	/**
	 * 方法: initTitle <br>
	 * 描述: 初始化页面标题 <br>
	 * 作者: ws <br>
	 * 时间: 2015-5-24 下午5:46:11
	 */
	private void initTitle() {
		txtTitle = (TextView) findViewById(R.id.title_text_nav);

		txtTitle.setText("保险续保");

		ivBack = (ImageView) findViewById(R.id.title_back);
		ivBack.setOnClickListener(this);
	}

	private void initView() {
		mLinearLayoutSelectType = (LinearLayout) findViewById(R.id.owner_bxxb_selecttype);
		mLinearLayoutSelectType.setOnClickListener(this);

		msBrand = (TextView) findViewById(R.id.exchange_brand);
		mSelectDate=(EditText)findViewById(R.id.owner_bxxb_xzsj);
		mSelectDate.setOnTouchListener(new OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) { 
					 
			          AlertDialog.Builder builder = new AlertDialog.Builder(ActivityBxxb.this); 
			          View view = View.inflate(ActivityBxxb.this, R.layout.date_time_dialog, null); 
			          final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker); 
			          final TimePicker timePicker = (android.widget.TimePicker) view.findViewById(R.id.time_picker); 
			          builder.setView(view); 
			 
			          Calendar cal = Calendar.getInstance(); 
			          cal.setTimeInMillis(System.currentTimeMillis()); 
			          datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); 
			 
			          timePicker.setIs24HourView(true); 
			          timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); 
			          timePicker.setCurrentMinute(Calendar.MINUTE); 
			 
			          if (v.getId() == R.id.et_appoint_date) { 
			              final int inType = mSelectDate.getInputType(); 
			              mSelectDate.setInputType(InputType.TYPE_NULL); 
			              mSelectDate.onTouchEvent(event); 
			              mSelectDate.setInputType(inType); 
			              mSelectDate.setSelection(mSelectDate.getText().length()); 
			                 
			              builder.setTitle("选取起始时间"); 
			              builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() { 
			 
			                  @Override 
			                  public void onClick(DialogInterface dialog, int which) { 
			 
			                      StringBuffer sb = new StringBuffer(); 
			                      sb.append(String.format("%d-%02d-%02d",  
			                              datePicker.getYear(),  
			                              datePicker.getMonth() + 1, 
			                              datePicker.getDayOfMonth())); 
			 
			                      mSelectDate.setText(sb); 
			                         
			                      dialog.cancel(); 
			                  } 
			              }); 
			                 
			          } 
			             
			          Dialog dialog = builder.create(); 
			          dialog.show(); 
			      } 
					return true;
			}});
		
		mUserName=(EditText)findViewById(R.id.newcar_price);
		mPhone=(EditText)findViewById(R.id.newcar_paytype);
		msBrand1=(TextView)findViewById(R.id.owner_bxxb_srpp);
		msSerial=(TextView)findViewById(R.id.owner_bxxb_series);
		msType=(TextView)findViewById(R.id.owner_bxxb_srkx);
		
		mNextStep=(Button)findViewById(R.id.exchange_submit);
		mNextStep.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				//ActivityAppointDrive agr= (ActivityAppointDrive)_context;
				//agr.openFragment(new fragmentappointdrive2());
				try{
					HttpExecuteJson http = new HttpExecuteJson(ActivityBxxb.this, mSubListListener);
					RequestParams rps=new RequestParams();
					rps.addBodyParameter("uid", AppContext.getInstance().getUserId()+"");
					rps.addBodyParameter("brand",StringUtils.utf8Encode( msBrand.getText().toString()));
					rps.addBodyParameter("series",StringUtils.utf8Encode( msSerial.getText().toString()));
					rps.addBodyParameter("model",StringUtils.utf8Encode(msType.getText().toString()));
					rps.addBodyParameter("plate",StringUtils.utf8Encode(msType.getText().toString()));
					rps.addBodyParameter("mil",StringUtils.utf8Encode(msType.getText().toString()));
					rps.addBodyParameter("type","5");
					rps.addBodyParameter("name",StringUtils.utf8Encode(mUserName.getText().toString()));
					rps.addBodyParameter("tel",StringUtils.utf8Encode(mPhone.getText().toString()));
					rps.addBodyParameter("buyDate",mSelectDate.getText().toString());
					http.post(ServiceHelper.AppointSave, rps);
				}catch(Exception e){}
			}});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			finish();
			break;

		case R.id.owner_bxxb_selecttype:
			type = 4;
			getDatas(ServiceHelper.BXXBXZLX);
			break;
		}
	}

	private void getDatas(String url) {
		try {
			HttpExecuteJson http = new HttpExecuteJson(this,
					mNewCarBoutiqueListener);
			Map<String, Object> rps = new HashMap<String, Object>();
			rps.put("uid", AppContext.getInstance().getUserId());
			Logger.i(url);
			http.get(url, rps);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private ResultInfo mResultInfo;
	private httpReturnJson mNewCarBoutiqueListener = new httpReturnJson() {

		@Override
		public void onSuccess(String result) {
			Logger.json(result);
			ResultInfo resultInfo = null;
			try {
				resultInfo = new Gson().fromJson(result,
						new TypeToken<ResultInfo>() {
						}.getType());
				if ((resultInfo != null)
						&& (resultInfo.msg
								.equals(ServiceHelper.msg_code_sucess))) {
					try {
						mResultInfo = resultInfo;

						mDatas = JsonUtil.fromJsonArray(
								JsonUtil.toJson(mResultInfo.data),
								CarSelectInfo.class);
						Message msg = new Message();
						msg.obj = mDatas;
						msg.what = type;
						mHandler.sendMessage(msg);

					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		@Override
		public void onFailure(int error, String msg) {

		}

		@Override
		public void onCancel() {

		}
	};

	private TextView msBrand;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 111111:
			msBrand.setText(((CarSelectInfo) data.getExtras().get("select")).name);
			break;

		}
	}
	
	private httpReturnJson mSubListListener = new httpReturnJson() {
		@Override
		public void onFailure(int error, String msg) {
			UIHelper.ToastMessage(ActivityBxxb.this, "预约失败！" + msg);
		}

		@Override
		public void onCancel() {
			// TODO Auto-generated method stub
			UIHelper.ToastMessage(ActivityBxxb.this, "预约失败！");
		}

		public void onSuccess(String result) {
			// TODO Auto-generated method stub
			// UIHelper.ToastMessage(_context,"总条数=" + result + "");
			DoJsonSub(result);
		}
	};
	
	/*
	 * 提交预约
	 */
	private void DoJsonSub(String json) {
		ResultInfo edv = null;
		try {
			edv = new Gson().fromJson(json, new TypeToken<ResultInfo>() {
			}.getType());
			if ((edv != null)
					&& (edv.msg.equals(ServiceHelper.msg_code_sucess))) {
				UIHelper.ToastMessage(ActivityBxxb.this, "预约成功！");
				finish();
			} else {
				UIHelper.ToastMessage(ActivityBxxb.this, "预约失败！"+edv.msg);

			}
		} catch (Exception e) {
			e.printStackTrace();
			UIHelper.ToastMessage(ActivityBxxb.this, "预约失败！"+e.getMessage());
		}
	}

}
